<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      class="a1"
    >
      <el-form-item label="订单编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker
          v-model="range"
          type="datetimerange"
          range-separator="至"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="订单状态">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态">
          <el-option label="已取消" :value="0"></el-option>
          <el-option label="待支付" :value="1"></el-option>
          <el-option label="已支付" :value="2"></el-option>
          <el-option label="已发货" :value="3"></el-option>
          <el-option label="确认收货" :value="4"></el-option>
          <el-option label="申请退款" :value="5"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="收货人手机号" prop="consigneePhone">
        <el-input
          v-model="queryParams.consigneePhone"
          placeholder="请输入收货人手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          class="daochu"
          @click="handleExport"
          v-hasPermi="['cancel:supplier:order:export']"
          >导出</el-button
        >
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['cancel:order:orderSends']"
          >批量发货</el-button
        >
      </el-col> -->
    </el-row>
    <el-card>
      <div>
        <el-tabs v-model="queryParams.status" @tab-click="handleClick">
          <el-tab-pane label="全部" name="-1"></el-tab-pane>
          <el-tab-pane label="待付款" name="1"></el-tab-pane>
          <el-tab-pane label="待发货" name="2"></el-tab-pane>
          <el-tab-pane label="待收货" name="3"></el-tab-pane>
          <el-tab-pane label="已完成" name="4"></el-tab-pane>
        </el-tabs>
        <!-- 列表 -->
        <el-table v-loading="loading" :data="articlesList">
          <el-table-column label="订单编号" align="center" prop="sn" />

          <el-table-column label="订单类型" align="center" prop="type">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.type == 2" type="success"
                >实物订单</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="用户信息" align="center">
            <template slot-scope="scope">
              <div>
                <div>{{ scope.row.consigneeName }}</div>
                <div>{{ scope.row.consigneePhone }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center">
            <template slot-scope="scope">
              <el-tag type="primary" v-if="scope.row.status == 1"
                >待付款</el-tag
              >
              <el-tag type="primary" v-if="scope.row.status == 2"
                >待发货</el-tag
              >
              <el-tag type="primary" v-if="scope.row.status == 3"
                >待收货</el-tag
              >
              <el-tag type="primary" v-if="scope.row.status == 4"
                >确认收货</el-tag
              >
              <el-tag type="primary" v-if="scope.row.status == 5"
                >申请退款</el-tag
              >
              <el-tag type="primary" v-if="scope.row.status == 6"
                >退款完成</el-tag
              >
              <el-tag type="primary" v-if="scope.row.status == 7"
                >已评价</el-tag
              >
              <el-tag type="primary" v-if="scope.row.status == 8"
                >退款失败</el-tag
              >
              <el-tag type="primary" v-if="scope.row.status == 9"
                >拆单中</el-tag
              >
              <el-tag type="primary" v-if="scope.row.status == 10"
                >拆单失败</el-tag
              >
              <el-tag type="primary" v-if="scope.row.status == 11"
                >拆单完成</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="商品信息" align="center" width="200">
            <template slot-scope="scope">
              <div
                v-for="item in scope.row.goodsList"
                :key="item.id"
                style="display: flex; align-items: center; margin: 0 auto"
              >
                <div>
                  <el-image
                    style="width: 80px; height: 80px"
                    :src="item.previewImg"
                    fit="fit"
                  ></el-image>
                </div>
                <div style="width: 90px; margin-left: 10px; text-align: left">
                  <div>{{ item.productName }}</div>
                  <div>{{ item.skuMsg }}</div>
                  <div>￥ {{ item.shopPrice }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="订单金额"
            align="center"
            prop="moneyAmount"
            v-if="$auth.hasPermi('cancel:order:company')"
          ></el-table-column>
          <el-table-column
            label="原价"
            align="center"
            prop="originalMoneyAmount"
            v-if="$auth.hasPermi('cancel:order:company')"
          ></el-table-column>
          <el-table-column
            label="优惠金额"
            align="center"
            prop="giveMoneyAmount"
            v-if="$auth.hasPermi('cancel:order:company')"
          ></el-table-column>
          <el-table-column align="center" prop="payTime" label="支付时间">
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handldeise(scope.row)"
                v-if="scope.row.status >= 2"
                v-hasPermi="['cancel:supplier:order:createDelivery']"
                >发货单</el-button
              >

              <el-button
                size="mini"
                type="text"
                v-if="
                  scope.row.status == 2 ||
                  scope.row.status == 3 ||
                  scope.row.status == 5
                "
                @click="handldeRefund(scope.row)"
                v-hasPermi="['cancel:order:refundOrder']"
                >退款</el-button
              >
              <el-button
                type="text"
                size="mini"
                icon="el-icon-tickets"
                v-hasPermi="['cancel:supplier:order:detail']"
                @click="handldetail(scope.row)"
                >查看详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          :showSearch.sync="showSearch"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getData"
        />
      </div>
    </el-card>

    <!-- 查看详情 -->
    <el-drawer
      title="发货单"
      :visible.sync="openDelis"
      direction="rtl"
      :before-close="handleClose"
    >
      <div style="padding: 10px">
        <el-form
          ref="form"
          :model="formOne"
          :rules="sendRules"
          label-width="80px"
        >
          <el-form-item label="发货类型">
            <el-select v-model="formOne.deliveryType" placeholder="请选择">
              <el-option label="首次" :value="1"> </el-option>
              <el-option label="补发" :value="2"> </el-option>
              <el-option label="换货" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="发货商品">
          <el-select v-model="goodsId" placeholder="请选择">
            <el-option
              v-for="item in goodsList"
              :key="item.goodsId"
              :label="item.productName"
              :value="item.goodsId"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
          <!-- 备注 -->
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formOne.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入备注"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">创建发货单</el-button>
          </el-form-item>
        </el-form>
        <el-form ref="fahuoForm" :model="fahuoForm" label-width="80px">
          <el-form-item label="物流公司" prop="company">
            <el-select v-model="fahuoForm.company" placeholder="请选择物流公司">
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.logisticsName"
                :value="item.logisticsName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物流单号" prop="logisticsNumber">
            <el-input
              v-model="fahuoForm.logisticsNumber"
              placeholder="请输入物流单号"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitFahuo"
              >提交发货单</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
    <el-dialog title="发货单" width="500px" append-to-body>
      <el-form
        ref="form"
        :model="formOne"
        :rules="sendRules"
        label-width="110px"
      >
        <el-form-item label="发货类型" prop="deliveryType">
          <el-select v-model="formOne.deliveryType" placeholder="请选择">
            <el-option label="首次" :value="1"> </el-option>
            <el-option label="补发" :value="2"> </el-option>
            <el-option label="换货" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formOne.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">创建发货单</el-button>
        </el-form-item>

        <!-- <el-form-item label="物流公司" prop="company">
          <el-select v-model="formOne.company" placeholder="请选择物流公司">
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.logisticsName"
              :value="item.logisticsName"
            ></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="订单详情"
      :visible.sync="openDetail"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
    >
      <order-detail :key="orderId" :orderId="orderId"></order-detail>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="openDetail = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 退款 -->
    <el-dialog title="退款" :visible.sync="openRe" width="600px" append-to-body>
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="110px"
      >
        <el-form-item label="退款金额" prop="refundPrice">
          <el-input
            v-model="refundForm.refundPrice"
            placeholder="请输入退款金额"
            type="number"
          />
        </el-form-item>
        <el-form-item label="是否退积分" prop="isRePoints">
          <el-radio-group v-model="refundForm.isRePoints">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款原因" prop="refundMsg">
          <el-input
            v-model="refundForm.refundMsg"
            placeholder="请输入退款原因"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div style="padding-left: 110px">
        提示:订单总金额为{{ row.moneyAmountTotal }}元，包含商品金额{{
          row.moneyAmount
        }}元和邮费{{ row.postageAmount }}元
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="tkLoad" @click="submitRefundForm"
          >确 定</el-button
        >
        <el-button @click="openRe = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { orderList, ordership, refundOrder } from "@/api/system/orderSuper";
import { showLogistics } from "@/api/order/logistics";
import OrderDetail from "./components/orderDetail.vue";
import { getToken } from "@/utils/auth";
export default {
  name: "OrderSuper",
  data() {
    return {
      tkLoad: false,
      openDetail: false,
      // 查询参数
      articlesList: [],
      loading: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        status: "-1",
      },
      range: [],
      // 开关
      total: 0,
      ids: [],
      formOne: {},
      fahuoForm: {},
      openDelis: false,
      showSearch: true,
      // 物流公司列表
      companyList: [],
      orderId: "",

      //商品列表
      goodsList: [],
      //选中的商品id
      goodsId: "",
      //退款
      openRe: false,
      refundForm: {},
      refundRules: {
        refundPrice: [
          { required: true, message: "请输入退款金额", trigger: "blur" },
        ],
        refundMsg: [
          { required: true, message: "请输入退款原因", trigger: "blur" },
        ],
      },
      row: {},
      // 订单发货
      sendRules: {
        company: [
          { required: true, message: "请输入物流公司名称", trigger: "blur" },
        ],
        companyCode: [
          { required: true, message: "请输入物流公司编号", trigger: "blur" },
        ],
        logisticsNumber: [
          { required: true, message: "请输入订单编号", trigger: "blur" },
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/cancel/order/orderSends",
      },
    };
  },
  mounted() {
    this.getData();
  },
  components: {
    OrderDetail,
  },
  computed: {},
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1;
      const [startTime, endTime] = this.range;
      this.queryParams.startTime = startTime;
      this.queryParams.endTime = endTime;
      this.getData();
    },
    handleClick(tab, event) {
      console.log(tab.name);
      // this.resetQuery();
      this.queryParams.status = tab.name;
      this.queryParams.pageNum = 1;
      this.getData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.range = [];
      this.queryParams = {
        sn: null,
        status: null,
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getData() {
      this.loading = true;
      orderList(this.queryParams).then((res) => {
        this.total = res.total;
        this.loading = false;
        this.articlesList = res.rows;
      });
    },
    //物流公司列表
    getListLogistics() {
      showLogistics().then((res) => {
        this.companyList = res.data;
      });
    },
    //退款
    handldeRefund(row) {
      const { id } = row;
      this.row = row;
      this.refundForm = {
        orderId: id,
        isRePoints: 0,
        refundPrice: null,
        refundMsg: null,
      };
      this.openRe = true;
    },
    submitRefundForm() {
      this.$refs["refundFormRef"].validate((valid) => {
        if (valid) {
          this.tkLoad = true;
          refundOrder(this.refundForm)
            .then((res) => {
              this.$modal.msgSuccess("退款成功");
              this.openRe = false;
              this.getData();
              this.tkLoad = false;
            })
            .catch(() => {
              this.tkLoad = false;
            });
        }
      });
    },
    handleExport() {
      const [startTime, endTime] = this.range;
      if (startTime == undefined || endTime == undefined) {
        this.$modal.msgError("请选择开始时间和结束时间");
        return false;
      }
      const { pageNum, pageSize, ...rest } = this.queryParams;
      this.download(
        "/cancel/order/supplier/export",
        {
          ...rest,
          startTime,
          endTime,
        },
        `user_${new Date().getTime()}.xlsx`
      );
      // residentexportOrder(this.queryParams).then((res) => {});
    },

    // 发货
    handldeise(row) {
      // this.getListLogistics();
      const { sn, id } = row;
      this.formOne.orderId = id;
      this.formOne.items = row.goodsList;
      this.$router.push({
        path: "deliveryNote",
        query: {
          id,
        },
      });
    },
    handleClose(done) {
      done();
    },
    //查看详情
    handldetail(row) {
      const { id } = row;
      console.log(id);
      this.orderId = id;
      this.openDetail = true;
    },
    submitFahuo() {
      this.$refs["fahuoForm"].validate((valid) => {
        if (valid) {
          ordership(this.fahuoForm, this.formOne.orderId).then((response) => {
            this.$modal.msgSuccess("提交发货单成功");
            this.fahuoForm = {};
            this.getData();
          });
        }
      });
    },
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          ordership(this.formOne, this.formOne.orderId).then((response) => {
            this.$modal.msgSuccess("创建发货单成功");
            this.formOne = {};
            this.getData();

            this.getListLogistics();
          });
        }
      });
    },
    cancel() {
      this.openDelis = false;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "/cancel/order/importTemplate",
        {},
        `order_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>

<style scoped>
/* .mb8 {
  margin-top: 10px;
  padding-left: 15px;
} */
.bnt {
  margin-top: 5px;
}
.images {
  width: 80px;
  height: 80px;
}
.a1 {
  margin: 10px 0 0 15px;
}
.daochu {
  margin-left: 24px;
}
</style>
